package com.mijie.tag;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import org.apache.log4j.Logger;

import com.mijie.core.Paging;

public class PagingTag extends SimpleTagSupport {

	private static Logger logger = Logger.getLogger(PagingTag.class);
	
	private String paging;
	private String var;
	private String index;
	
	@SuppressWarnings("unchecked")
	@Override
	public void doTag() throws JspException, IOException {
		PageContext pageContext = (PageContext) this.getJspContext();
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		if(paging!=null){
			Paging<Object> p = (Paging<Object>) request.getAttribute(paging);
			if(p==null) return;
			List<Object> list = p.getList();
			if(list!=null && !list.isEmpty()){
				int i = 1;
				for(Object o : list){
					if(o!=null){
						pageContext.setAttribute(var, o);
						if(index!=null) 
							pageContext.setAttribute(index, i++);
						getJspBody().invoke(null);
					}
				}
			}
		}
	}

	public String getPaging() {
		return paging;
	}

	public void setPaging(String paging) {
		this.paging = paging;
	}

	public String getVar() {
		return var;
	}

	public void setVar(String var) {
		this.var = var;
	}

	public String getIndex() {
		return index;
	}

	public void setIndex(String index) {
		this.index = index;
	}

}
